package com.itheima.web.filters;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class BeanFactory {
//    定义储存service对象的map集合
    public static  Map<String,Object> cache=new HashMap<>();
//    加载bean.properties属性文件
//    创建properties对象
    static {
    Properties properties = new Properties();
//    加载配置文件
    InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");

    try {
        properties.load(is);
    } catch (IOException e) {
        e.printStackTrace();
    }
//    获取所有的key并遍历
    Set<String> names = properties.stringPropertyNames();
    names.forEach(name->{
//        读取配置文件内容
        String className = properties.getProperty(name);
        Object bean = null;
        try {
             bean = Class.forName(className).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        储存在map集合中
        cache.put(name,bean);
    });
}
public static<T> T getBean(String name ,Class<T>tClass){
        return (T) cache.get(name);
}
}
